<!DOCTYPE html>
<html>
<head>
  <title>FAQ</title>
  <meta charset="UTF-8">
</head>
<body>
<h2>常见问题</h2>
<input type="text" id="searchInput" placeholder="搜索问题...">
<button onclick="searchFAQs()">搜索</button>
<div id="faqList"></div>
<script>
  let userId = null;

  function fetchFAQs() {
    fetch(`/api/faq?userId=${userId}`)
            .then(response => response.json())
            .then(data => {
              const faqList = document.getElementById('faqList');
              faqList.innerHTML = '';
              if (data && data.length > 0) {
                data.forEach(faq => {
                  const faqDiv = document.createElement('div');
                  faqDiv.innerHTML = `<h3>${faq.question}</h3><p>${faq.answer}</p>`;
                  faqList.appendChild(faqDiv);
                });
              } else {
                faqList.innerHTML = '<p>没有找到常见问题</p>';
              }
            });
  }

  function searchFAQs() {
    const keyword = document.getElementById('searchInput').value;
    fetch(`/api/faq/search?keyword=${keyword}&userId=${userId}`)
            .then(response => response.json())
            .then(data => {
              const faqList = document.getElementById('faqList');
              faqList.innerHTML = '';
              if (data && data.length > 0) {
                data.forEach(faq => {
                  const faqDiv = document.createElement('div');
                  faqDiv.innerHTML = `<h3>${faq.question}</h3><p>${faq.answer}</p>`;
                  faqList.appendChild(faqDiv);
                });
              } else {
                faqList.innerHTML = '<p>没有找到匹配的常见问题</p>';
              }
            });
  }

  // 页面加载时获取所有 FAQ
  window.onload = function() {
    const urlParams = new URLSearchParams(window.location.search);
    userId = urlParams.get('userId');
    if (userId) {
      fetchFAQs();
    } else {
      alert('请先登录');
      window.location.href = 'login.html';
    }
  };
</script>
</body>
</html>